import traceback

from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_ROW_HEIGHT_RULE
from docx import Document
from docx.shared import Pt,Inches, Cm, RGBColor
from docx.oxml.ns import qn
import datetime
import time
# 创建一个新的Word文档
import docx
from pdf2image import convert_from_path
from PIL import ImageOps
from bid.generate.models import ExFile, ExBid
from zentao.settings import ROOT_FOLDER

#业绩生成
def generate_pmProject(data_dict, extra_data, save_path, bid_id):

    doc = Document()

    # 序号
    title_id = '99.'
    # title_id = ''

    # 定义标题和正文的样式

    # project_count = len(data_dict)
    project_people= extra_data['pm']
    # 计算总金额
    people_professional=extra_data['professional']
    total_amount = extra_data['total_amount']
    # 构建内容字符串
    # content0 = f"我公司具有丰富的信息化项目建设相关业绩，共提供近年完成的同类项目业绩共 {project_count} 个，业绩总金额为：{total_amount} 万元。"
    content0 = f"电网管理平台(法律事务应用 V2.0-合规管理等)建设部分与电网管理平台(风 控数智化管理应用 V1.0) 建设部分的项目负责人均为 {project_people}。 {project_people}具备丰富的 同类项目经验，业绩金额累计{total_amount}万元，具备{people_professional}职称。"

    # styles = [
    #     ("(一十五) 项目负责人情况", content0, 15.5, True, WD_PARAGRAPH_ALIGNMENT.CENTER, 14, False, WD_PARAGRAPH_ALIGNMENT.LEFT),
    #     ("15.1. 项目负责人业绩", None, 14.5, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT),
    #     ("15.1.1.  项目负责人的信息化建设项目业绩总表", None, 14, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT),
    #    ("15.1.2 项目负责人的信息化建设项目业绩证明", None, 14, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT)
    # ]
    styles = [
        ("（九十九）项目负责人情况", content0, 15.5, True, WD_PARAGRAPH_ALIGNMENT.CENTER, 14, False, WD_PARAGRAPH_ALIGNMENT.LEFT, 1),
        (f"{title_id}1. 项目负责人业绩", None, 14.5, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT, 2),
        (f"{title_id}1.1. 项目负责人的信息化建设项目业绩总表", None, 14, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False,WD_PARAGRAPH_ALIGNMENT.LEFT, 3),
        (f"{title_id}1.2 项目负责人的信息化建设项目业绩证明", None, 14, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT, 3),
        (f"{title_id}2. 项目负责人素质", None, 14.5, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT,2),
        ]

    # 添加标题和正文到文档中
    for style in styles:
        title, content, title_font_size, title_bold, title_alignment, content_font_size, content_bold, content_alignment, level = style

        # 添加标题
        paragraph = doc.add_heading(level=level)
        run = paragraph.add_run(title)
        run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
        run.font.italic = False  # 关闭斜体

        run.font.size = Pt(title_font_size)
        run.bold = title_bold
        paragraph.alignment = title_alignment
        # 设置字体为宋体
        run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
        paragraph.paragraph_format.line_spacing = 1.5
        # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
        paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
        paragraph.paragraph_format.space_after = Pt(0)  # 设置段后间距为5磅


        # 添加正文
        if content is not None:
            paragraph = doc.add_paragraph()
            run = paragraph.add_run(content)
            run.font.size = Pt(content_font_size)
            run.bold = content_bold
            paragraph.alignment = content_alignment
            # 设置字体为宋体
            run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
            paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍
            paragraph.paragraph_format.first_line_indent = Pt(24)  # 设置首行缩进为2个字符（大约24磅）

        #添加表格数据
        # if title=="15.1.1.  项目负责人的信息化建设项目业绩总表":
        if title==f"{title_id}1.1. 项目负责人的信息化建设项目业绩总表":
            table = doc.add_table(rows= len(data_dict) + 1, cols=7)

            # 设置表格列宽
            col_widths = [1.5, 2.8, 3.43, 2.2, 2.04, 2.93, 2.58]
            # 应用每列的宽度
            for col, width in zip(table.columns, col_widths):
                for cell in col.cells:
                    cell.width = Cm(width)

            # 设置表格样式以显示框线
            table.style = 'Table Grid'
            headers = ["序号","项目名称","合同名称","甲方单位","乙方项目负责人","项目验收年份","项目金额（万元）"]

            # 填写表头
            for i, header in enumerate(headers):
                cell = table.cell(0, i)
                cell.text = header
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.bold = True  # 设置表头文本加粗
                        run.font.size = Pt(12)  # 设置字体为小四号
                        run.font.name = '宋体'
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')


            def set_cell_font(cell, text):
                cell.text = text
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.size = Pt(12)  # 设置字体为小四号
                        run.font.name = '宋体'
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')


            def table_wr(i):
                # 填写内容
                row = table.rows[i + 1]  # 第二行用于填写内容
                for ind_j,j in enumerate(headers):
                    if j=="序号":
                        set_cell_font(row.cells[0], str(i + 1))  # 序号
                    else:
                        set_cell_font(row.cells[ind_j], str(data_dict[i][j]))
            for i in range(len(data_dict)):
                table_wr(i)

            # 添加分节符
            doc.add_section()

    #图片插入
    # 添加截图信息
    def image_write(data):
        paragraph = doc.add_paragraph()
        # 在段落中添加图片
        # 假设图片文件名为'image.png'，位于当前目录下
        image_path = data
        run = paragraph.add_run()
        # 一直插图片
        judge = False
        while not judge:
            try:
                run.add_picture(image_path, width=Inches(6))  # 设置图片宽度为4英寸
                judge = True
            except:
                print(image_path)
        paragraph.alignment = 1

    # 图片裁剪
    def trim_and_add_border(image):
        # 将图片转换为灰度图像，便于处理
        grayscale_image = image.convert('L')

        width = grayscale_image.width
        height = grayscale_image.height

        # 找到需要裁剪的边界
        def find_borders(img):
            invert_img = ImageOps.invert(img)
            bbox = invert_img.getbbox()
            return bbox

        borders = find_borders(grayscale_image)

        if not borders:
            borders = (0, 0, width, height)
        else:
            left, top, right, bottom = borders
            left = max(0, left - width // 20)
            right = min(width, right + width // 20)
            top = max(0, top - height // 20)
            bottom = min(height, bottom + height // 20)

            if (bottom - top) / (right - left) > 1.414:
                new_width = int((bottom - top) / 1.415)
                left = min(left, max(0, (width - new_width) // 2))
                right = max(right, min(width, new_width + (width - new_width) // 2))

                # print((bottom - top) / (right - left))

            borders = (left, top, right, bottom)
        # print(borders)
        trimmed_image = image.crop(borders)

        return trimmed_image

    def pdf_image(pdf_path):
        # st = time.time()
        images = convert_from_path(pdf_path)
        # 遍历所有图片并将其添加到Word文档中
        for image in images:
            image = trim_and_add_border(image)
            # image.save('/media/977GB/wcj_work/投标文件生成/团队生成.png')
            # 保存图片到临时文件
            temp_image_path = 'temp_image.png'
            image.save(temp_image_path, 'JPEG')

            # 将图片添加到Word文档
            # doc.add_picture(temp_image_path, width=Inches(6))  # 设置插入的图片大小为6英寸
            # 在文档中添加一个新的段落
            paragraph = doc.add_paragraph()

            # 设置段落的对齐方式为居中
            paragraph.alignment = 1  # 1代表居中对齐

            # 创建一个运行并添加图片
            run = paragraph.add_run()
            # 一直插图片
            judge = False
            while not judge:
                try:
                    run.add_picture(temp_image_path, width=Inches(6))  # 设置插入的图片大小为6英寸
                    judge = True
                except:
                    traceback.format_exc()


    # # 15.1.2. 项目负责人的信息化建设项目业绩证明
    # # 15.1.2.1. 深圳供电局有限公司信息中心 2023 年电网管理平台 (综合域 V2.0-公务管理、信 访维稳等) 建设项目
    for i in range(len(data_dict)):
        # title1="15.1.2."+str(i+1)+data_dict[i]["项目名称"]
        title1=f"{title_id}1.2."+str(i+1)+data_dict[i]["项目名称"]
        styles = [(title1, None, 12, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT, 4)]
        # t_content=["合同关键页","验收证书"]
        t_content=list(data_dict[i].keys())[7:]
        for index,t_c in enumerate(t_content):
            title_name=f'({index+1}) {t_c}'
            sty=(title_name, None, 12, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT, 5)
            styles.append(sty)
        for style in styles:
            title, content, title_font_size, title_bold, title_alignment, content_font_size, content_bold, content_alignment, level = style

            # 添加标题
            paragraph = doc.add_heading(level=level)
            run = paragraph.add_run(title)
            run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
            run.font.italic = False  # 关闭斜体
            run.font.size = Pt(title_font_size)
            run.bold = title_bold
            paragraph.alignment = title_alignment
            # 设置字体为宋体
            run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
            paragraph.paragraph_format.line_spacing = 1.5

            # 悬挂缩进1cm
            paragraph.paragraph_format.left_indent = Cm(1.46)
            paragraph.paragraph_format.first_line_indent = Cm(-1.46)

            paragraph.paragraph_format.space_before = Pt(10)  # 设置段前间距为5磅
            paragraph.paragraph_format.space_after = Pt(0)  # 设置段后间距为5磅

            for tem_c in t_content:
                # "中标通知书","合同扫描件","合同转签协议","验收证书"
                _c = data_dict[i][tem_c]
                if tem_c in title:
                    if _c.endswith('.pdf'):
                        pdf_image(_c)
                    else:
                        image_write(_c)

    #添加项目负责人素质
    diathesis = extra_data['pm_info']

    styles = [(f"{title_id}2. 项目负责人素质", None, 14.5, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.LEFT,2),]

    # 添加标题和正文到文档中
    title, content, title_font_size, title_bold, title_alignment, content_font_size, content_bold, content_alignment, level = styles[0]

    # 添加标题
    paragraph = doc.add_heading(level=level)
    run = paragraph.add_run(title)
    run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
    run.font.italic = False  # 关闭斜体

    run.font.size = Pt(title_font_size)
    run.bold = title_bold
    paragraph.alignment = title_alignment
    # 设置字体为宋体
    run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
    run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
    paragraph.paragraph_format.line_spacing = 1.5
    # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
    paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
    paragraph.paragraph_format.space_after = Pt(0)  # 设置段后间距为5磅

    # 添加子标题
    paragraph = doc.add_heading(level=level+1)
    run = paragraph.add_run(f"{title_id}2.1. 项目负责人简历")
    run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
    run.font.italic = False  # 关闭斜体

    run.font.size = Pt(title_font_size)
    run.bold = title_bold
    paragraph.alignment = title_alignment
    # 设置字体为宋体
    run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
    run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
    paragraph.paragraph_format.line_spacing = 1.5
    # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
    paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
    paragraph.paragraph_format.space_after = Pt(0)  # 设置段后间距为5磅

    # 添加表格
    table = doc.add_table(rows=len(data_dict) + 5, cols=8)

    # 设置表格列宽
    col_widths = [1.49, 1.88, 1.37, 1.32, 2.43, 1.89, 2.20, 2.19]
    # 应用每列的宽度
    for col, width in zip(table.columns, col_widths):
        for cell in col.cells:
            cell.width = Cm(width)

    # 设置表格样式以显示框线
    table.style = 'Table Grid'
    headers = ["姓名", extra_data['pm'], "性别", extra_data['sex'], "学位", extra_data['degree'], "本项目中职务",extra_data['position']]

    #设置行高
    for i in [0,1,2,3,-1]:
        table.rows[i].height = Cm(0.92)
        table.rows[i].height_rule = WD_ROW_HEIGHT_RULE.AT_LEAST

    # 填写表头
    for i, header in enumerate(headers):
        cell = table.cell(0, i)
        cell.text = header
        cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
        for paragraph in cell.paragraphs:
            for run in paragraph.runs:
                run.font.size = Pt(12)  # 设置字体为小四号
                run.font.name = '宋体'
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            paragraph.paragraph_format.space_before = Pt(6)  # 设置段前间距为5磅
            paragraph.paragraph_format.space_after = Pt(6)  # 设置段后间距为5磅
            paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍

    #添加第二行（证书行）
    for i, text in zip([0, 3], ['项目负责人相关证书名称','；'.join(diathesis['资格证书'].keys())]):
        cell = table.cell(1, i)
        cell.text = text
        cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
        for paragraph in cell.paragraphs:
            for run in paragraph.runs:
                run.font.size = Pt(12)  # 设置字体为小四号
                run.font.name = '宋体'
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            paragraph.paragraph_format.space_before = Pt(6)  # 设置段前间距为5磅
            paragraph.paragraph_format.space_after = Pt(6)  # 设置段后间距为5磅
            paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍

        if i==0:
            # 合并从 (0,0) 到 (0,2) 的单元格（即第一行前3列）
            cell.merge(table.cell(1, 2))
        elif i ==3:
            cell.merge(table.cell(1, 7))

    #添加第三行
    cell = table.cell(2, 0)
    cell.text = '已完成项目情况'
    cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    for paragraph in cell.paragraphs:
        for run in paragraph.runs:
            run.font.size = Pt(12)  # 设置字体为小四号
            run.font.name = '宋体'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        paragraph.paragraph_format.space_before = Pt(6)  # 设置段前间距为5磅
        paragraph.paragraph_format.space_after = Pt(6)  # 设置段后间距为5磅
        paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍

    cell.merge(table.cell(2, 7))

    #格式化业绩
    ls = [['序号', '项目名称', '合同（服务）对方名称', '合同金额（万元）']]
    for i, project in enumerate(data_dict, start=1):
        ls.append([i, project['项目名称'], project['甲方单位'], project['项目金额（万元）']])

    row_index = 3
    for i, row_data in enumerate(ls):
        for index, text in zip([0,1,5,7],row_data):
            cell = table.cell(row_index, index)
            cell.text = str(text)
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.size = Pt(12)  # 设置字体为小四号
                    run.font.name = '宋体'
                    run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                paragraph.paragraph_format.space_before = Pt(6)  # 设置段前间距为5磅
                paragraph.paragraph_format.space_after = Pt(6)  # 设置段后间距为5磅
                paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍

            if index == 1:
                cell.merge(table.cell(row_index, 4))
            elif index == 5:
                cell.merge(table.cell(row_index, 6))
        row_index += 1

    #最后一行
    for i, text in zip([0, 7], ['合计（万元）',total_amount]):
        cell = table.cell(row_index, i)
        cell.text = str(text)
        cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
        for paragraph in cell.paragraphs:
            for run in paragraph.runs:
                run.bold = True  # 设置表头文本加粗
                run.font.size = Pt(12)  # 设置字体为小四号
                run.font.name = '宋体'
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            paragraph.paragraph_format.space_before = Pt(6)  # 设置段前间距为5磅
            paragraph.paragraph_format.space_after = Pt(6)  # 设置段后间距为5磅
            paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍

        if i==0:
            # 合并从 (0,0) 到 (0,2) 的单元格（即第一行前3列）
            cell.merge(table.cell(row_index, 6))

    #添加图片
    index = 2
    for key, value in diathesis.items():
        # 添加子标题
        paragraph = doc.add_heading(level=level + 1)
        run = paragraph.add_run(f"{title_id}2.{index}. {key}")

        run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
        run.font.italic = False  # 关闭斜体

        run.font.size = Pt(title_font_size)
        run.bold = title_bold
        paragraph.alignment = title_alignment
        # 设置字体为宋体
        run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
        paragraph.paragraph_format.line_spacing = 1.5
        # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
        paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
        paragraph.paragraph_format.space_after = Pt(0)  # 设置段后间距为5磅

        if isinstance(value,list):
            for path in value:
                if path.endswith('.pdf'):
                    pdf_image(path)
                else:
                    image_write(path)
        else:
            sub_index = 1
            for sub_key, sub_value in value.items():
                # 添加子标题
                paragraph = doc.add_heading(level=level + 2)
                run = paragraph.add_run(f"{title_id}2.{index}.{sub_index}. {sub_key}")
                sub_index += 1

                run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
                run.font.italic = False  # 关闭斜体

                run.font.size = Pt(title_font_size)
                run.bold = title_bold
                paragraph.alignment = title_alignment
                # 设置字体为宋体
                run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
                paragraph.paragraph_format.line_spacing = 1.5
                # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
                paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
                paragraph.paragraph_format.space_after = Pt(0)  # 设置段后间距为5磅

                for path in sub_value:
                    if path.endswith('.pdf'):
                        pdf_image(path)
                    else:
                        image_write(path)

        index += 1

    #修改页边距
    for i in range(len(doc.sections)):
        doc.sections[i].top_margin = Cm(0.71)
        doc.sections[i].bottom_margin = Cm(0.71)
        doc.sections[i].left_margin = Cm(2.35)
        doc.sections[i].right_margin = Cm(2.35)

    # 保存文档的路径
    current_time = datetime.datetime.now()
    filename = current_time.strftime(save_path)
    # 保存文档的路径
    filepath_modified = filename
    doc.save(filepath_modified)

    # 将文件添加到文件数据库表中
    file = ExFile.objects.create(
        path=filepath_modified.replace(ROOT_FOLDER, ''),
        type='docx',
        comment='',
        uploadDate=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    )

    # 更新数据库
    ExBid.objects.filter(id=bid_id).update(pmProject=file)



